<script setup lang="ts">
import { ref,watchEffect, onMounted, reactive } from 'vue'
import request from '@utils/request'
import { useMainStore } from '@/store/index'
import { useMainLogin } from '@/store/user'
import * as mars3d from "mars3d"
import axios from 'axios'
import * as XLSX from 'xlsx/xlsx.mjs'
import { renderAsync } from 'docx-preview'
import downloade from "@/api/downloade"
import SceneControl from "@/utils/site.js"
import FileSaver from 'file-saver'
import pdfjsLib from 'pdfjs-dist/build/pdf.js'
import { PDFViewer } from 'pdfjs-dist/web/pdf_viewer'
import 'pdfjs-dist/web/pdf_viewer.css'
import videojs from "video.js"
import "video.js/dist/video-js.css"
import type { VideoJsPlayerOptions } from 'video.js'
import { initWheelScale } from '@/utils/vWheelScale'
import { UploadFilled } from '@element-plus/icons-vue'

// 接口
import { files,delFiles,changeFrom,postFrom,searchElement } from "@/api/plotsInfo"
import { delElement,changeElement } from "@/api/plots"

// 定义全局变量类型
declare global {
  interface Window {
    graphicLayer: any;
  }
}

// 定义类型
interface RestaurantItem {
  value: string;
}

interface info {
  name: string;
  category: string;
  colorChecked: string;
  elementId: string;
  folderId: string;
  childrenSort: number;
  type: string;
  geom: string;
  remark: string;
  color: string;
  distance: string;
}

const store = useMainStore()
const user = useMainLogin()
const uploadRef = ref<UploadInstance>()
const videoPlayerRef = ref<InstanceType<typeof videoPlayer>>()
const myPlayer = ref(null)
const videoSrc = ref(null)

// 拖拽相关
const initDrag = reactive({ x: 0, y: 0 })
const dragHandle = (data: any) => {
  // 处理拖拽回调
  // console.log('Drag data:', data)
}

// 缩放相关
const initWheelScale = reactive({ scale: 1 })
const wheelScaleChange = (data: any) => {
  // 处理缩放回调
  // console.log('Scale data:', data)
}

const mainInfo = ref<info>({}) //数据源汇总
const TitleEditing = ref<boolean>(false)
const categoryEditing = ref<boolean>(false)
const reslutMeasure = ref<string>('')
const position = ref<any>([])
const colorList = ref<any>(['#05a5f1','#03b41b','#f19d23','#d9001b','#8401ff'])
const dialogFormVisible = ref<boolean>(false)
const form = ref<any>({name: '',url:'',type:'链接',space:1})
const rules = ref<any>({
  name:  [ {required: true,trigger: 'blur', message: "请在输入链接名称" }],
  url: [{ required: true, trigger: 'blur', message: "请在输入正确的链接" }],
})
const urlList = ref<any>([])
const urlListIndex = ref<number>(-1)
const addFrom = ref<FormInstance>()
const isUpFiles = ref<boolean>(false)
const isSort = ref<boolean>(true)
const imgList = ref<any>([])
const fileList = ref<any>([])
const videoList = ref<any>([])
const otherFileList = ref<any>([])
const photoUrl = ref<string>('')
const photoShow = ref<boolean>(false)
const PdfUrl = ref<string>('/test2.pdf')
const pdfShow = ref<boolean>(false)
const wordShow = ref<boolean>(false)
const excelShow = ref<boolean>(false)
const excelData = ref<any>([])
const excelDataKey = ref<any>()
const videoShow = ref<boolean>(false)
const allFilesList = ref<any>([])

// 文档预览
const previewType = ref<string>()
const fillFlag = ref<boolean>(true)
const showNotes = ref<boolean>(false)

onMounted(() => {
  initVideo()
})

// 初始化videojs
const initVideo = () => {
  const options: VideoJsPlayerOptions = {
    language: 'zh-CN', // 设置语言
    controls: true, // 是否显示控制条
    preload: 'auto', // 预加载
    autoplay: false, // 是否自动播放
    fluid: false, // 自适应宽高
    src: videoSrc.value, // 要嵌入的视频源的源 URL
    objectFit: 'cover', // 同css object-fit，作用于video标签
    notSupportedMessage: 'Ajiang此视频暂无法播放，请稍后再试' //允许覆盖Video.js无法播放媒体源时显示的默认信息。
  }
  if (videoPlayerRef.value) {
    // 创建 video 实例
    myPlayer.value = videojs(videoPlayerRef.value, options)
  }
}

const getFilesList = () => {
  searchElement(mainInfo.value.elementId).then(res => {
    if(res.code === 200) {
      urlList.value = res.rows.filter(item => {return item.type == '链接'})
      imgList.value = res.rows.filter(item => {return item.type == '图片'})
      fileList.value = res.rows.filter(item => {return item.type == '文档'})
      videoList.value = res.rows.filter(item => {return item.type == '视频'})
      otherFileList.value = res.rows.filter(item => { return item.type == '其他' })
    }
  })
}

const getGraphic = () => {
  TitleEditing.value = categoryEditing.value = false
  allFilesList.value = []
  try {
    let geom = window.graphicLayer.getGraphicById(store.graphicId)
    mainInfo.value.name = geom.options.name
    mainInfo.value.category = geom.options.attr.category
    mainInfo.value.colorChecked = geom.options.style.color
    mainInfo.value.elementId = geom.options.attr.elementId
    mainInfo.value.folderId = geom.options.attr.folderId
    mainInfo.value.childrenSort = geom.options.attr.childrenSort
    mainInfo.value.type = store.type = geom.options.type!=undefined? geom.options.type:'billboard'
    mainInfo.value.geom = JSON.parse(JSON.stringify(geom.options.attr.geom))
    mainInfo.value.remark = geom.options.attr.remark
    mainInfo.value.color = geom.options.style.color
    showNotes.value = geom.options.attr.showNotes!=undefined ? geom.options.attr.showNotes : false
    fillFlag.value = geom.options.style.opacity==0.3?true:false
    if(geom.options.type == "billboard") {
      let lat = String(geom.getCoordinate()[0]);
      let latDu = lat.split(".")[0];
      let latFen = String(("0." + lat.split(".")[1]) * 60);
      let latMiao = (("0." + latFen.split(".")[1]) * 60).toFixed(0);

      let lng = String(geom.getCoordinate()[1]);
      let lngDu = lng.split(".")[0];
      let lngFen = String(("0." + lng.split(".")[1]) * 60);
      let lngMiao = (("0." + lngFen.split(".")[1]) * 60).toFixed(0);

      position.value =  [latDu + "°" + latFen.split(".")[0] + "′" + latMiao + "″",lngDu + "°" + lngFen.split(".")[0] + "′" + lngMiao + "″"];
    }else if (geom.options.type == "polyline") {

      reslutMeasure.value = mars3d.MeasureUtil.formatDistance(geom.distance)
    }else {
      reslutMeasure.value = mars3d.MeasureUtil.formatArea(geom.area)
      mainInfo.value.distance = geom.distance>1000?(geom.distance/1000).toFixed(2) + '公里':geom.distance.toFixed(2) + '米'
    }
    getFilesList()
  } catch (error) {

  }
}

const categoryOption = (queryString: string, cb: any) => {
  const results = queryString? user.category.filter(createFilter(queryString)):user.category
  cb(results)
}

const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}

const endEdit = () => {
  let geom = window.graphicLayer.getGraphicById(store.graphicId)
  if(store.saved && mainInfo.value.name == geom.options.name && mainInfo.value.remark == geom.options.attr.remark) {
    store.graphicOperate = '结束编辑'
    window.graphicLayer.stopEditing()
    clearEdit()
  } else {
    ElMessageBox.confirm('您还未保存该注记, 是否保存?', '提示', {
      confirmButtonText: '保存',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      save()
    }).catch(() => {
      unsave()
      clearEdit()
    })
  }
}

const clearEdit = () => {
  store.saved = true
  store.graphicId = ''
  TitleEditing.value = categoryEditing.value = false
  allFilesList.value = []
  urlList.value = []
  imgList.value = []
  fileList.value = []
  videoList.value = []
  otherFileList.value = []
}

const save = () => {
  var item = {
    name:mainInfo.value.name,
    type:mainInfo.value.type,
    sort:mainInfo.value.childrenSort,
    folderId:mainInfo.value.folderId,
    elementId:mainInfo.value.elementId,
    isOpen:true,
    show:true,
    category:mainInfo.value.category,
    remark:mainInfo.value.remark,
    geom:''
  }
  let categoryFlag = false
  user.category.map(item => {
    if(item.value == mainInfo.value.category)categoryFlag =  true
  })
  !categoryFlag?user.category.push({value:mainInfo.value.category}):''
  var graphic = window.graphicLayer.getGraphicById(store.graphicId)
  graphic.options.attr.geom = ''
  graphic.options.name = graphic._name = mainInfo.value.name
  showNotes.value&&mainInfo.value.remark?graphic.setStyle({label: {text: mainInfo.value.name+'：'+mainInfo.value.remark}}):graphic.setStyle({label: {text: mainInfo.value.name}})
  graphic.options.attr.remark = mainInfo.value.remark
  graphic.options.attr.category = mainInfo.value.category
  graphic.options.attr.showNotes = showNotes.value
  postKmlData(graphic, item)
}

// 修改时上传kml文件
const postKmlData = (graphic, item) => {
  var instance = SceneControl.getInstance()
  var filename = mainInfo.value.name + '.kml'
  const geojson = window.graphicLayer.getGraphicById(store.graphicId).toGeoJSON()
  if (mainInfo.value.type == "polygon") {
    geojson.geometry.coordinates[0].push(geojson.geometry.coordinates[0][0])
  }
  geojson.properties.geom = geojson.properties.remark = ''
  geojson.properties.style = JSON.stringify(geojson.properties.style)
  const data = instance.tokml(geojson)
  const blob = new Blob([data])
  var geofile = new File([blob], filename, {
    type: 'application/json',
    lastModified: Date.now()
  });
  files(geofile, '其他', store.graphicId).then(res => {
    editElement(graphic, item, res.data)
  })
}

// 修改要素
const editElement = (graphic, item, kmlData) => {
  graphic.options.attr.ossId = kmlData.ossId
  graphic.options.attr.kmlName = kmlData.fileName
  graphic.options.attr.kmlUrl = kmlData.url
  graphic.options.attr.geom = JSON.stringify(graphic)
  item.geom = JSON.stringify(graphic)
  item.userId = user.userId
  changeElement(item).then(res => {
    if(res.code === 200) {
      item.leaf = true
      store.graphicOperate = '修改'
      ElMessage({type: 'success',message: '保存成功!'});
    }
  })
}
const unsave = () => {
  let geom =  typeof(window.graphicLayer.getGraphicById(store.graphicId).options.attr.geom) == 'string'?
  JSON.parse(window.graphicLayer.getGraphicById(store.graphicId).options.attr.geom):
  window.graphicLayer.getGraphicById(store.graphicId).options.attr.geom
  let attrGeom = JSON.parse(JSON.stringify(geom))
  geom.attr.geom = attrGeom
  geom.style.color = mainInfo.value.color
  geom.style.outlineColor = mainInfo.value.color
  window.graphicLayer.removeGraphic(window.graphicLayer.getGraphicById(store.graphicId))
  if(mainInfo.value.type == "polygon"){
    const entity = new mars3d.graphic.PolygonEntity(geom)
    window.graphicLayer.addGraphic(entity)
  }else if(mainInfo.value.type == "polyline") {
    const entity = new mars3d.graphic.PolylineEntity(geom)
    window.graphicLayer.addGraphic(entity)
  }else {
    const entity = new mars3d.graphic.BillboardEntity(geom)
    window.graphicLayer.addGraphic(entity)
  }
  ElMessage({showClose: true,message: '取消修改'});
  store.graphicOperate = '结束编辑'
}

const del = () => {
  ElMessageBox.confirm('是否删除当前要素?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delElement(mainInfo.value.elementId).then(res=> {
      if(res.code === 200) {
        ElMessage({type: 'success',message: '删除成功!'});
        store.graphicOperate = '删除'
      }
    })
  }).catch(() => {
    ElMessage({type: 'message',message: '取消删除'});
  });
}

const selectColor = (item) => {
  store.saved = false
  mainInfo.value.colorChecked = item
  window.graphicLayer.getGraphicById(store.graphicId).setOptions({
      style: {
          color:item,
          outlineColor:item,
      }
  })

}

const goPage = (url)=>{window.open(url)}

const editUrl = (item,index) => {
  dialogFormVisible.value = true
  form.value.name = item.name
  form.value.url = item.url
  form.value.fileId = item.fileId
  urlListIndex.value = index
}

const delUrl = (item,index) => {
  ElMessageBox.confirm('是否删除当前文件?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
  }).then(() => {
        delFiles(item.fileId).then(res => {
          if(res.code === 200) {
            urlList.value.splice(index,1)
            ElMessage({type: 'success',message: '链接删除成功!'});
          }
        })
  }).catch(() => {
    ElMessage({type: 'message',message: '取消删除'});
  });
}

const cancelAddUrl = (addFrom) => {
  addFrom.resetFields()
  dialogFormVisible.value = false
  form.value = { name: '', url: '', type: '链接', space: 1 }
}

const addUrl = (addFrom) => {
  addFrom.validate().then(valid=> {
    if(!valid) return
    form.value.elementId = mainInfo.value.elementId
    if (urlListIndex.value == -1) {
      postElementFile(form.value, '链接保存成功!', '链接')
    }else {
      changeFrom(form.value).then(res => {
        if(res.code === 200) {
          dialogFormVisible.value = false
          urlList.value[urlListIndex.value] = form.value
          urlListIndex.value = -1
          form.value = {name: '',url:'',type:'链接',space:1}
          ElMessage({type: 'success',message: '链接修改成功!'});
        }
      })
    }
  })
}

// 修改排序方式
const changeSort = () => {
  isSort.value = !isSort.value
  if (isSort.value) {
    timeSort(imgList.value)
    timeSort(fileList.value)
    timeSort(videoList.value)
    timeSort(otherFileList.value)
  } else {
    sortChinese(imgList.value,'name')
    sortChinese(fileList.value,'name')
    sortChinese(videoList.value,'name')
    sortChinese(otherFileList.value,'name')
  }
}

const timeSort = (arr) => {
  arr.sort((item1, item2) => {
    return item1.fileId*1 - item2.fileId*1;
  })
}

const sortChinese = (arr, dataLeven) => {
  arr.sort((item1, item2) => {
    return getValue(item1,dataLeven).localeCompare(getValue(item2,dataLeven), 'zh-CN');
  })
}

const getValue = (option, dataLeven) => {
  if (!dataLeven) return option
  return dataLeven.split('.').reduce((data, key) => data[key], option) + ''
}

const getFiles = (type) => {
  type.forEach(item => {
    downloade.oss(item.ossId)
  })
}

const delallFiles = (type) => {
  ElMessageBox.confirm('是否删除当前文件?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
  }).then(() => {
    store.saved = false
    var fileId = []
    type.forEach(item =>{
        fileId.push(item.fileId)
    })
    if(fileId.length>0) {
      delFiles(fileId).then(res => {
        if(res.code === 200) {
          getFilesList()
          ElMessage({type: 'success',message: '删除成功!'});
        }
      })
    }
  }).catch(() => {
    ElMessage({type: 'message',message: '取消删除'});
  });
}

// 预览
const preview = (url,name) => {
  let index = name.lastIndexOf('.')
  let str = name.substr(index + 1)
  let newUrl = '/obs/' + url.split('http://192.168.110.100:9000/')[1]
  if(newUrl.indexOf('.pdf') > 0) {
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.943/build/pdf.worker.min.js'
    pdfShow.value = true
    PdfUrl.value = newUrl
    getPdf()
  }else if (['png', 'jpg','jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(str.toLowerCase()) !== -1) {
    photoShow.value = true
    photoUrl.value = url
  }else if(['AVI', 'mov','rmvb', 'rm', 'FLV', 'mp4', '3GP'].indexOf(str.toLowerCase()) !== -1){
    videoShow.value = true
    videoSrc.value = newUrl
    myPlayer.value.pause()
    // videoPlayer.dispose()
    myPlayer.value.reset()
    setTimeout(() => {
      myPlayer.value.src([
        {
          src: videoSrc.value,
          // type: "application/x-mpegURL"  //type可以不写，一旦写了一定要符合否则报错
        }
      ])
      myPlayer.value.load()
      myPlayer.value.play()
    }, 10)
  }else {
    axios({
      method: "get",
      responseType: "blob", // 因为是流文件，所以要指定blob类型
      url: newUrl, // 自己的服务器，提供的一个word下载文件接口
      // headers:{}
    }).then(res => {
      if(newUrl.indexOf('.docx') > 0||newUrl.indexOf('.doc') > 0||newUrl.indexOf('.txt') > 0){
        previewType.value = 'docx'
        try {
          let childRef = document.getElementById('childRef');
          renderAsync(res.data, childRef); // 渲染到页面
        }catch (error) {
          ElMessage({type: 'error',message: '文档为空!'});
        }
        wordShow.value = true
      }else if(newUrl.indexOf('.xlsx') > 0||newUrl.indexOf('.xls') > 0){
        previewType.value = 'xlsx'
        readExcelToJson(res.data).then((res) => {
          excelData.value = res
          excelDataKey.value = Object.keys(excelData.value[0])
          excelShow.value = true
          //如果是用elementUI的上传，文件上传成功之后，重置上传文件列表，this.$refs.upload.clearFiles();
        });
      }
    });
  }
  ElNotification({title: '按 ESC 退出预览'})
  document.onkeydown = (e) => {
    if(e.key == "Escape") {
      if (photoShow.value) {
        setPotoShowPosition()
      }
      pdfShow.value = photoShow.value = excelShow.value = wordShow.value = videoShow.value = false
      myPlayer.value.pause()
      document.onkeydown = null
    }
  }
}

// 关闭显示照片按钮
const closePotoShow = () =>{
  photoShow.value = false
  setPotoShowPosition()
}

// 重新设置照片显示的位置
const setPotoShowPosition = () => {
  let photoUrlEle = document.getElementById('photoUrlShow')
  photoUrlEle.style.top = "50%"
  photoUrlEle.style.left = "50%"
}

const getPdf = async () => {
  const container = document.getElementById('pageContainer')
  // 实例化pdf视图
  const pdfViewer = new PDFViewer({
    container: container,
  })
  // 加载pdf文件
  const loadingTask = pdfjsLib.getDocument(PdfUrl.value)
  // 生成文档
  const pdf = await loadingTask.promise
  // 开始绘制到dom
  pdfViewer.setDocument(pdf)
}

// 封装函数
const readExcelToJson = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const result = e.target?.result;
      if (result instanceof ArrayBuffer) {
        let data = new Uint8Array(result);
        let workbook = XLSX.read(data, {
          type: "array"
        });
        //将Excel 第一个sheet内容转为json格式
        let worksheet = workbook.Sheets[workbook.SheetNames[0]];
        let json = XLSX.utils.sheet_to_json(worksheet);
        resolve(json);
      } else {
        reject(new Error('Invalid file data'));
      }
    };
    reader.readAsArrayBuffer(file);
  });
}
const getFile = (item) => {
  downloade.oss(item.ossId)
}

const delFile = (item,index,type) => {
  ElMessageBox.confirm('是否删除当前文件?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
  }).then(() => {
      store.saved = false
      delFiles(item.fileId).then(res => {
        if(res.code === 200) {
          type.splice(index,1)
          ElMessage({type: 'success',message: '删除成功!'});
        }
      })
  }).catch(() => {
    ElMessage({type: 'message',message: '取消删除'});
  });
}

const uploadClose = () => {
  allFilesList.value = []
  /* allFilesList.value.forEach((item, index) => {
    if(item.percentage == 100) {
      allFilesList.value.splice(index,1)
    }
  }) */
}

const onBeforeUpload = (file) => {
    const isLt1M = file.size / 1024 / 1024 < 50;
    if (!isLt1M) {
      ElMessage({type: 'error',message: '上传文件大小不能超过 50MB!'});
    } else {
      if (file.size > user.basicInfo.remainingUsageSpaceB)  return ElMessage.error('空间不足')
      var arr = {
        uid:file.uid,
        name:file.name,
        percentage:0,
        upload:true
      }
      allFilesList.value.push(arr)
    }
}

const handleUpload = (file) => {
  let filesListIndex = allFilesList.value.findIndex(item => item.uid == file.file.uid)
  allFilesList.value[filesListIndex].finish = false
  allFilesList.value[filesListIndex].upload = true
  allFilesList.value[filesListIndex].percentage = 0
  let type = ''
  let index = file.file.name.lastIndexOf('.')
  let str = file.file.name.substr(index + 1)
  if( ['png', 'jpg','jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(str.toLowerCase()) !== -1) {
    type = '图片'
  }else if( ['doc', 'docx','xls', 'xlsx', 'pdf'].indexOf(str.toLowerCase()) !== -1) {
    type = '文档'
  }else if( ['AVI', 'mov','rmvb', 'rm', 'FLV', 'mp4', '3GP'].indexOf(str.toLowerCase()) !== -1) {
    type = '视频'
  }else {
    type = '其他'
  }
  let data = new FormData();
  data.append('file', file.file);
  data.append('type', type);
  data.append('elementId', mainInfo.value.elementId);
  request({
      url: '/resource/oss/upload',
      headers: {
          "Content-Type": "multipart/form-data",
          isToken: false,
      },
      method: 'post',
      data:data,
      onUploadProgress: function (e) {
        allFilesList.value[filesListIndex].percentage = e.progress.toFixed(2)*100
      }
  }).then(res => {
    if (res.code === 200) {
        allFilesList.value[filesListIndex].percentage = 100
        allFilesList.value[filesListIndex].finish = true
        let elementData = {
          ossId: res.data.ossId,
          url:res.data.url,
          name: res.data.fileName,
          type: type,
          space: res.data.fileSize
        }
        postElementFile(elementData,'文件上传成功!',type)
      }else {
        allFilesList.value[filesListIndex].upload = false
        allFilesList.value[filesListIndex].file = file
        ElMessage({type: 'error',message: '上传文件失败!'});
      }
  })
}

const postElementFile = (data,msg,type) => {
  data.elementId = mainInfo.value.elementId
  data.userId = user.userId
  postFrom(data).then(res=> {
    if(res.code === 200) {
      if (type == '链接') {
        dialogFormVisible.value = false
        form.value.fileId = res.data
        // isSort.value = true
        urlList.value.push(form.value)
        urlListIndex.value = -1
        form.value={name: '',url:'',type:'链接',space:1}
      } else {
        getFilesList()
      }
      ElMessage({type: 'success',message: msg});
    }
  })
}

const printKML = () => {
    var instance = SceneControl.getInstance()
    var filename = mainInfo.value.name + '.kml'
    const geojson = window.graphicLayer.getGraphicById(store.graphicId).toGeoJSON()
    if (mainInfo.value.type == "polygon") {
      geojson.geometry.coordinates[0].push(geojson.geometry.coordinates[0][0])
    }
    geojson.properties.geom = geojson.properties.remark = ''
    geojson.properties.style = JSON.stringify(geojson.properties.style)
    const data = instance.tokml(geojson)
    const blob = new Blob([data])
    FileSaver.saveAs(blob, filename)
}

const endEditBtn = () => {
  window.graphicLayer.stopEditing()
}

const fillChange = () => {
  store.saved = false
  fillFlag.value?window.graphicLayer.getGraphicById(store.graphicId).setStyle({opacity:0.3}):window.graphicLayer.getGraphicById(store.graphicId).setStyle({opacity:0.01})
}

watchEffect(() => {
  if(store.graphicOperate == '开始编辑'&&store.graphicId != ''){
    getGraphic();
    store.isOpenTabel = false;
  }
  if(store.graphicOperate == '结束编辑'){
    clearEdit();
  }
  if(store.graphicOperate == '结束修改'){
    endEdit();
  }
})
</script>

<template>
<div :class="store.graphicOperate === '开始编辑' && !store.isOpenTabel ?'polyMainInfoBox show':'polyMainInfoBox'">
  <div @click="endEditBtn()" class="close"><i class="iconfont icon-cuo"></i></div>
  <div class="title_box interval">
      <el-tooltip
        class="box-item"
        effect="dark"
        content="单击修改"
        placement="bottom-start"
      >
        <div class="title" @click="TitleEditing = true;" v-show="!TitleEditing">
          <span>{{ mainInfo.name }}</span>
        </div>
      </el-tooltip>
    <div class="title" v-show="TitleEditing">
      <div class="textInputWrapper">
        <input @blur="onInputBlur" @keydown.enter="TitleEditing = false" style="font-size: 24px;background: transparent;box-sizing: border-box;" placeholder="Type Here" type="text" class="textInput" v-model="mainInfo.name"></div>
    </div>
    <div style="display: flex; align-items: center;margin-left: 15px;">
      类别：
      <el-tooltip
        class="box-item"
        effect="dark"
        content="单击修改"
        placement="bottom-start"
      >
      <span v-show="!categoryEditing" style="cursor: pointer;" @click="categoryEditing = true">{{ mainInfo.category }}</span>
    </el-tooltip>
      <div v-show="categoryEditing"><el-autocomplete style="width:120px" v-model="mainInfo.category" :fetch-suggestions="categoryOption" clearable class="inline-input w-50" /></div>
    </div>

  </div>
  <!-- 点线面 坐标 长度 面积 -->
  <div class="geometryInfo interval">
    <div v-show="mainInfo.type == 'polyline'" style="display: flex; align-items: center;">
      <!-- <img class="pic" src="@/../public/img/线-小.png" alt=""/> -->
      <div class="geoinfo">线长：{{ reslutMeasure }}</div>
    </div>
    <div v-show="mainInfo.type == 'polygon'" style="display: flex; align-items: center;">
      <!-- <img class="pic" src="@/../public/img/面-小.png" alt="" /> -->
      <div class="geoinfo" style="margin-right: 20px;">面积：{{ reslutMeasure }}</div>
      <div class="geoinfo">周长：{{ mainInfo.distance }}</div>
    </div>
    <div v-show="mainInfo.type == 'billboard'"  class="geoinfo">
        <div>经度：{{position[0]}}
            <i style="display: inline-block;width: 20px;">
                </i>纬度：{{position[1]}}
        </div>
    </div>
  </div>

  <!-- 信息 -->
  <div class="info interval">
    <div class="color_box" style="margin: 10px 0;width: 230px;">
        <div class="color_outline" v-for="(item,index) in colorList" :key="index">
            <span class="bg">
                <span class="color" :style="'background-color:' + item"  @click="selectColor(item)">
                    <span class="checked" v-show="mainInfo.colorChecked == item? true:false"><i style="font-size: 20px;" class="iconfont icon-xuanze-"></i></span>
                </span>
            </span>
        </div>
        <div v-show="mainInfo.type=='polygon'"><span>填充</span><el-switch v-model="fillFlag" @change="fillChange" /></div>
    </div>

    <div class="flex_base" style="font-size: 16px;">
      <span style="margin-right:.5rem">备注</span>
      <span style="margin-right: .5rem;">标注上图</span><el-switch v-model="showNotes" />
    </div>
    <div class="editinfo">
      <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容" v-model="mainInfo.remark" @input="mainInfo.textInput" ></el-input>
    </div>
  </div>

  <div class="bottomBtn">
    <div class="btn" @click="printKML">导出范围</div>
    <div class="btn save" @click="save()">保存</div>
    <div class="btn del" @click="del()">删除</div>
  </div>

  <!-- 链接 -->
  <div class="info link interval">
    <div class="InfoBoxTitle">
      <span>链接</span>
      <div @click="dialogFormVisible = true" class="addUrlBtn"><img src="@/assets/image/urlUpload.png" alt=""></div>
    </div>
    <div class="ListBox">
        <div class="listItem" v-for="(item,index) in urlList" :key="index">
          <span>{{item.name}}</span>
          <div class="button flex_base">
            <div @click="goPage(item.url)" class="img-position cursor-point ml5" >
              <img class="icon-size20" src="@/assets/image/urlTurnTo.png" alt="">
            </div>
            <div @click="editUrl(item,index)"  class="img-position cursor-point ml5">
              <img class="icon-size20" src="@/assets/image/urlReset.png" alt="">
            </div>
            <div @click="delUrl(item,index)" class="img-position cursor-point ml5" >
              <i class="iconfont icon-cuo" style="font-size: 20px;"></i>
              <!-- <img style="width: 25px;height: 25px;" src="@/assets/image/close.png" alt=""> -->
            </div>
          </div>
        </div>
    </div>

    <!-- 新增链接的表单 -->
    <el-dialog v-model="dialogFormVisible" title="链接">
      <el-form :model="form" :rules="rules" ref="addFrom">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地址" prop="url">
          <el-input v-model="form.url" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAddUrl(addFrom)">取消</el-button>
          <el-button type="primary" @click="addUrl(addFrom)">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  <div class="info link interval">
    <div class="InfoBoxTitle">
      <span>文件</span>
      <div @click="isUpFiles=!isUpFiles" class="addUrlBtn"><img src="@/assets/image/filesUpload.png" alt=""></div>
      <div :class="isSort? 'isSort check':'isSort'" @click="changeSort"><i class="iconfont icon-paixu"></i></div>
    </div>
  </div>

  <!-- 上传文件 -->
  <el-dialog v-model="isUpFiles" title="上传文件" @close="uploadClose">
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      drag
      action=" "
      multiple
      :show-file-list="false"
      :before-upload="onBeforeUpload"
      :http-request="handleUpload"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将文件拖到此处,或 <em>点击选择</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          文件大小请小于50Mb
        </div>
        <div class="filesList">
          <div class="item" v-for="item,index in allFilesList" :key="index">
            <span class="name">{{item.name}}</span>
            <div class="line" v-show="item.percentage != 100 && item.upload"><el-progress :percentage="item.percentage" /></div>
            <i v-show="!item.upload" @click="handleUpload(item.file)" class="iconfont icon-zhongxinjiazai"></i>
          </div>
        </div>
      </template>
    </el-upload>
  </el-dialog>
  <!-- 照片 -->
  <div class="secondary" v-show="imgList.length>0">
    <div class="info files">
      <div class="InfoBoxTitle">
        <span>照片</span>
        <div @click="getFiles(imgList)" style="margin-left: 10px;cursor: pointer;"><img src="@/assets/image/filesDownload.png" alt=""></div>
        <div @click="delallFiles(imgList)" class="isSort"><img src="@/assets/image/filesDet.png" alt=""></div>
      </div>
    </div>
    <div class="ListBox">
      <div class="photoItem listItem" v-for="(item,index) in imgList" :key="index">
        <el-tooltip class="box-item" effect="dark" :content="item.name" placement="top-start"><span>{{item.name}}</span></el-tooltip>
        <div class="button flex_base">
            <!-- <div @click="preview(item.url,item.name)" class="img-position cursor-point ml10" >
              <img class="icon-size20" src="@/assets/image/preview.png" alt="">
            </div> -->
            <div @click="getFile(item)" class="img-position cursor-point ml10" >
              <img class="icon-size20" src="@/assets/image/download.png" alt="">
              <!-- <download size="18px" theme="outline" fill="#3DBDA7"/> -->
            </div>
            <div @click="delFile(item,index,imgList)" class="img-position cursor-point ml10" >
              <!-- <img style="width: 25px;height: 25px;" src="@/assets/image/close.png" alt=""> -->
              <i class="iconfont icon-cuo" style="font-size: 20px;"></i>
            </div>
          </div>
      </div>
    </div>
  </div>
  <!-- 文档 -->
  <div class="secondary" v-show="fileList.length>0">
    <div class="info files">
      <div class="InfoBoxTitle">
        <span>文档</span>
        <div @click="getFiles(fileList)" style="margin-left: 10px;cursor: pointer;"><img src="@/assets/image/filesDownload.png" alt=""></div>
        <div @click="delallFiles(fileList)" class="isSort"><img src="@/assets/image/filesDet.png" alt=""></div>
      </div>
    </div>
    <div class="ListBox">
      <div class="photoItem listItem" v-for="(item,index) in fileList" :key="index">
        <el-tooltip class="box-item" effect="dark" :content="item.name" placement="top-start"><span>{{item.name}}</span></el-tooltip>
        <div class="button flex_base">
            <!-- <div @click="preview(item.url,item.name)" class="img-position cursor-point ml10" >
              <img class="icon-size20" src="@/assets/image/preview.png" alt="">
            </div> -->
            <div @click="getFile(item)" class="img-position cursor-point ml10" >
              <img class="icon-size20" src="@/assets/image/download.png" alt="">
            </div>
            <div @click="delFile(item,index,fileList)" class="img-position cursor-point ml10" >
              <!-- <img style="width: 25px;height: 25px;" src="@/assets/image/close.png" alt=""> -->
              <i class="iconfont icon-cuo" style="font-size: 20px;"></i>
            </div>
          </div>
      </div>
    </div>
  </div>
  <!-- 视频 -->
  <div class="secondary" v-show="videoList.length>0">
    <div class="info files">
      <div class="InfoBoxTitle">
        <span>视频</span>
        <div @click="getFiles(videoList)" style="margin-left: 10px;cursor: pointer;"><img src="@/assets/image/filesDownload.png" alt=""></div>
        <div @click="delallFiles(videoList)" class="isSort"><img src="@/assets/image/filesDet.png" alt=""></div>
      </div>
    </div>
    <div class="ListBox">
      <div class="photoItem listItem" v-for="(item,index) in videoList" :key="index">
        <el-tooltip class="box-item" effect="dark" :content="item.name" placement="top-start"><span>{{item.name}}</span></el-tooltip>
        <div class="button flex_base">
            <!-- <div @click="preview(item.url,item.name)" class="img-position cursor-point ml10" >
              <img class="icon-size20" src="@/assets/image/preview.png" alt="">
            </div> -->
            <div @click="getFile(item)" class="img-position cursor-point ml10" >
              <img class="icon-size20" src="@/assets/image/download.png" alt="">
            </div>
            <div @click="delFile(item,index,videoList)" class="img-position cursor-point ml10" >
              <!-- <img style="width: 25px;height: 25px;" src="@/assets/image/close.png" alt=""> -->
              <i class="iconfont icon-cuo" style="font-size: 20px;"></i>
            </div>
          </div>
      </div>
    </div>
  </div>
  <!-- 其他 -->
  <div class="secondary" v-show="otherFileList.length>0">
    <div class="info files">
      <div class="InfoBoxTitle">
        <span>其他</span>
        <div @click="getFiles(otherFileList)" style="margin-left: 10px;cursor: pointer;"><img src="@/assets/image/filesDownload.png" alt=""></div>
        <div @click="delallFiles(otherFileList)" class="isSort"><img src="@/assets/image/filesDet.png" alt=""></div>
      </div>
    </div>
    <div class="ListBox">
      <div class="photoItem listItem" v-for="(item,index) in otherFileList" :key="index">
        <el-tooltip class="box-item" effect="dark" :content="item.name" placement="top-start"><span>{{item.name}}</span></el-tooltip>
        <div class="button flex_base">
            <div @click="getFile(item)" class="img-position cursor-point ml10" >
              <img class="icon-size20" src="@/assets/image/download.png" alt="">
            </div>
            <div @click="delFile(item,index,otherFileList)" class="img-position cursor-point ml10" >
              <!-- <img style="width: 25px;height: 25px;" src="@/assets/image/close.png" alt=""> -->
              <i class="iconfont icon-cuo" style="font-size: 20px;"></i>
            </div>
          </div>
      </div>
    </div>
  </div>

  <!-- 预览文件 -->
  <div v-show="photoShow" class="docWrap">
    <i class="iconfont icon-cuo" @click="closePotoShow()"></i>
    <img id="photoUrlShow" v-drag:[initDrag]="dragHandle" v-wheelScale:[initWheelScale]="wheelScaleChange" :src="photoUrl" alt="" style="max-width:90%;min-width:30%;max-height: 100%;position: absolute;top: 50%;left: 50%;transform:translate(-50%,-50%)">
  </div>
  <div v-show="pdfShow" class="docWrap pdfDocWrap">
    <i class="iconfont icon-cuo" @click="pdfShow = false"></i>
    <!-- <iframe :src="PdfUrl" frameborder="0"></iframe> -->
    <div id="pageContainer">
      <div id="viewer" class="pdfViewer"></div>
    </div>
  </div>
  <div v-show="wordShow" class="docWrap">
    <i class="iconfont icon-cuo" @click="wordShow = false"></i>
    <div id="childRef"></div>
  </div>
  <!-- <div v-show="docShow" class="docWrap">
    <i class="iconfont icon-cuo" @click="docShow = false"></i>
    <div id="childDocRef"></div>
  </div> -->
  <div v-show="excelShow" class="docWrap excel">
    <i class="iconfont icon-cuo" @click="excelShow = false"></i>
    <el-table :data="excelData" style="width: 100%" border>
      <el-table-column
        v-for="(key, index) in excelDataKey"
        :key="index"
        :prop="key"
        :label="key"
      ></el-table-column>
    </el-table>
  </div>
  <div v-show="videoShow" class="docWrap" style="display: flex;align-items: center;">
    <i class="iconfont icon-cuo" @click="[videoShow = false,myPlayer.pause(),videoSrc=null]"></i>
    <!-- <iframe :src="PdfUrl" frameborder="0"></iframe> -->
    <video ref="videoPlayer" class="video-js video-js-style" style="margin: auto auto" :src="videoSrc">
      <!-- <source :src="videoSrc" /> -->
    </video>
  </div>

</div>
</template>

<style scoped>
.polyMainInfoBox {
  position: fixed;
  left: -100%;
  top: 0;
  width: 400px;
  height: 100vh;
  background: rgb(29, 30, 34,.8);
  transition: all .8s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  padding: 10px;
  z-index: 99;
  overflow: auto;
  color: #fff;
}
.show {
  left: 0;
}
.close {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
}
.title_box {
  display: flex;
  align-items: center;
}
.title {
  /* display: flex;
  align-items: center; */
  font-size: 24px;
  font-weight: 800;
  font-family: '庞门正道标题体3';
  cursor: pointer;
  max-width: 260px;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.textInputWrapper {
    position: relative;
    width: 180px;
    --accent-color: #3DBDA7;
}
.editTitleImg {
  margin: 0 20px;
  color: #fff;
  user-select: none;
  cursor: pointer;
}
.editTitle {
  margin: 0 20px;
  padding: 5px 20px;
  border-radius: 20px;
  font-size: 16px;
  color: #fff;
  background: #3DBDA7;
  user-select: none;
  cursor: pointer;
  font-family: '微软雅黑';
}
.info {
  font-size: 20px;
}
.InfoBoxTitle {
  display: flex;
}
.InfoBoxTitle img {
  width: 28px;
}
.addUrlBtn {
  cursor: pointer;
  user-select: none;
  margin-left: 20px;
}
.textInput {
  color: #fff;
}
.textInputWrapper {
  width: 120px;
}
.upFiles {
  line-height: 30px;
  user-select: none;
  margin-bottom: 10px;
}
.isSort {
  display: inline-block;
  vertical-align: bottom;
  cursor: pointer;
  width: 50px;
  text-align: center;
}
.isSort i{
  vertical-align: bottom;
  font-size: 20px;
}
.check {
  color: #3DBDA7;
}

/* 预览 */
.docWrap {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: auto;
  background-color: rgba(0, 0, 0,.5);
  text-align: center;
}
.docWrap .icon-cuo {
  position: fixed;
  top: 10px;
  right: 20px;
  /* color: #000; */
  overflow: hidden;
  z-index: 9;
  padding: 5px;
  font-size: 30px;
  font-weight: 600;
  cursor: pointer;
}
.docWrap .icon-cuo:hover {
  color: #ff0000;
}
.docWrap .video-js-style{
  width: 100%;
  height: 80%;
}
.excel {
  background: #fff;
  padding: 30px 20px;
  box-sizing: border-box;
}
.circleBtn {
  display: inline-block;
  vertical-align: middle;
  padding: 4px;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  overflow: hidden;
  text-align: center;
  line-height: 12px;
  margin: 0 4px;
  cursor: pointer;
}
.circleBtn .iconfont {
  font-size: 12px;
  vertical-align: middle;
}
.circleBtn.primary {
  background: #66adef;
  color: #fff;
}
.circleBtn.success {
  background: #4ec11e;
  color: #fff;
}
.circleBtn.text .iconfont{
  font-size: 20px;
}
/*  */
.editinfo {
    /* border: 1px solid rgba(38, 207, 117, 0.2); */
    margin: 0 0 15px 0;
    position: relative;
    resize: none;
}
.ListBox {
  min-height: 40px;
  margin-bottom: 20px;
}
.listItem {
  display: flex;
  flex: 1;
  height: 40px;
  line-height: 40px;
  align-items: center;
  justify-content: space-between;
  padding-left: 2rem;
}
.listItem span {
  max-width: 220px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/* bottom */
.bottomBtn {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
}
.bottomBtn .btn{
  display: inline-block;
  margin: 0 20px;
  padding: 5px 20px;
  color: #fff;
  background: #FD8C1A;
  border-radius: 5px;
  cursor: pointer;
  user-select: none;
}
.bottomBtn .del {
  background: #CC1E08;
}
.bottomBtn .save {
  background: #3DBDA7;
}
#pageContainer {
  position: absolute;
  margin: auto;
  width: 100%;
}

div.page {
  display: inline-block;
}
:deep(.pdfViewer .page) {
 border: none;
 max-width:calc(100% - 20px) !important;
}

:deep(.pdfViewer .page .canvasWrapper) ,
:deep(.pdfViewer .page .canvasWrapper canvas) {
 max-width:calc(100% - 20px) !important;
}
.pdfDocWrap{
 overflow-x:hidden !important;
}
.secondary {
  transform: translateX(10px);
  width: calc(100% - 10px);
}
.filesList{
  max-height: 200px;
  overflow: hidden;
  overflow-y: scroll;
}
</style>
